package com.example.towSpringBoot.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.towSpringBoot.annotation.RequiredPermission;
import com.example.towSpringBoot.common.Result;
import com.example.towSpringBoot.dto.EmployeeDto;
import com.example.towSpringBoot.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * @description: 校验权限拦截器
 * @author: xinTong
 * @create: 2024-02-15 23:16
 **/
@Component
public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取用户userId
        String userId = request.getHeader("userId");
        //2、从redis中获取用户信息
        String objEmployee = redisUtils.get("rbac:login_employee:" + userId);
        EmployeeDto employeeDto = JSON.parseObject(objEmployee, EmployeeDto.class);
        //3、判断是否是草鸡管理员
        if (employeeDto.getAdmin()){
            return true;
        }
        //4、获取当前访问方法, 如果方法上没有注解放行
        if (handler instanceof HandlerMethod){
            //5、获取方法上的注解
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
            // 判断注解是否为空（是否有注解）
            if (annotation == null){
                // 方法上没有注解放行
                return true;
            }
            // 方法上有注解
            //6、从redis中获取用户拥有权限表达式集合
            String objExpression = redisUtils.get("rbac:expression:" + userId);
            // 权限可能有多个，是集合
            ArrayList<String> arrayList = JSON.parseObject(objExpression, ArrayList.class);
            //7、当前注解上的权限是否包含在集合中，在则放行
            if (arrayList.contains(annotation.expression())){
                return true;
            }
            //8、集合中不存在则返回相应响应体
            Result result = new Result(403,"没有权限","fail",null);
            response.getWriter().write(JSON.toJSONString(result));
        }
        return false;
    }
}
